package com.ssyc.gsk_parents.activity;

import android.text.Editable;
import android.text.InputFilter;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;

import com.ssyc.common.base.BaseActivity;
import com.ssyc.common.base.BaseApplication;
import com.ssyc.common.bean.BusInfo;
import com.ssyc.common.http.HttpAdress;
import com.ssyc.common.http.HttpUtils;
import com.ssyc.common.manager.AccountUtils;
import com.ssyc.common.manager.PickerManager;
import com.ssyc.common.utils.DateUtils;
import com.ssyc.common.utils.GsonUtil;
import com.ssyc.common.utils.MaxTextLengthFilter;
import com.ssyc.common.utils.UiUtils;
import com.ssyc.common.view.dialog.CustomDialogManager;
import com.ssyc.gsk_parents.R;
import com.ssyc.gsk_parents.bean.ResultInfo;

import org.greenrobot.eventbus.EventBus;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import okhttp3.Call;

/**
 * 在线请假
 * Created by Administrator on 2018/6/20 0020.
 */

public class ParentsLeaveOnlineActivity extends BaseActivity implements View.OnClickListener {
    private ImageView ivBack;
    //开始时间
    private TextView tvStartTime;
    //结束时间
    private TextView tvEndTime;

    //输入框
    private EditText etInput;

    //显示输入框的文字
    private TextView tvNum;

    /**
     * 已批准5次,带批准1次
     */
    private TextView tvDetails;
    private Button btCommit;

    //记录选择的起始时间
    private String stratTime, endTime;


    //记录已批准次数和待批准次数
    private String approval, approvalPending;


    public static final String APPROVAL = "approval";

    public static final String APPROVALPENDING = "approvalPending";

    @Override
    protected boolean isNeedShowTitle() {
        return false;
    }

    @Override
    protected String setTitleText() {
        return null;
    }

    @Override
    protected int getContentLayout() {
        return R.layout.parent_activity_leave_new_online;
    }

    @Override
    protected void init() {
        showContent();

        //初始化视图
        initView();

        //获取传递的数据
        initIntent();

        //设置监听
        initListener();
    }


    /**
     * 初始化视图
     */
    public void initView() {
        ivBack = findViewById(R.id.iv_back);
        ivBack.setOnClickListener(this);
        tvStartTime = findViewById(R.id.tv_start_time);
        tvStartTime.setOnClickListener(this);
        tvEndTime = findViewById(R.id.tv_end_time);
        tvEndTime.setOnClickListener(this);
        tvDetails = findViewById(R.id.tv_details);
        btCommit = findViewById(R.id.bt_commit);
        btCommit.setOnClickListener(this);
        etInput = findViewById(R.id.et_input);
        tvNum = findViewById(R.id.tv_num);
    }

    /**
     * 获取传递的数据
     */
    private void initIntent() {
        approval = getIntent().getStringExtra(APPROVAL);
        approvalPending = getIntent().getStringExtra(APPROVALPENDING);

        //设置已经批准或者待批准的次数
        if (!TextUtils.isEmpty(approval) && !TextUtils.isEmpty(approvalPending)) {
            tvDetails.setText("已批准 " + approval + " 次," + "待批准 " + approvalPending + " 次");
        } else if (TextUtils.isEmpty(approval) && !TextUtils.isEmpty(approvalPending)) {
            tvDetails.setText("已批准 " + 0 + " 次," + "待批准 " + approvalPending + " 次");
        } else if (TextUtils.isEmpty(approval) && TextUtils.isEmpty(approvalPending)) {
            tvDetails.setText("已批准 " + 0 + " 次," + "待批准 " + 0 + " 次");
        } else if (!TextUtils.isEmpty(approval) && TextUtils.isEmpty(approvalPending)) {
            tvDetails.setText("已批准 " + approval + " 次," + "待批准 " + 0 + " 次");
        }
    }


    /**
     * 设置监听
     */
    private void initListener() {
        etInput.setFilters(new InputFilter[]{new MaxTextLengthFilter(201)});
        etInput.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void afterTextChanged(Editable editable) {
                String content = etInput.getText().toString().trim();
                if (!TextUtils.isEmpty(content)) {
                    if (content.length() > 199) {
                        tvNum.setText("200/200");
                    } else {
                        tvNum.setText(content.length() + "/200");
                    }
                } else {
                    tvNum.setText("0/200");
                }
            }
        });
    }


    /**
     * 页面控件点击事件
     *
     * @param v
     */
    @Override
    public void onClick(View v) {
        int id = v.getId();
        if (id == R.id.iv_back) {
            //返回
            finish();
        } else if (id == R.id.tv_start_time) {
            //开始时间
            showChooseTimePicker(1);
        } else if (id == R.id.tv_end_time) {
            //结束时间
            showChooseTimePicker(2);
        } else if (id == R.id.bt_commit) {
            //提交
            doCommitAction();
        }
    }


    /**
     * 提交的操作
     */
    private void doCommitAction() {
        //先判断是否选择了开始时间和结束时间
        if (TextUtils.isEmpty(stratTime)) {
            UiUtils.Toast("请完善请假信息", false);
            return;
        }

        if (TextUtils.isEmpty(endTime)) {
            UiUtils.Toast("请完善请假信息", false);
            return;
        }

        //判断结束时间是否大于开始时间
        Log.i("test", "endTime:" + DateUtils.getTime(endTime, "yyyy-M-dd"));
        Log.i("test", "stratTime:" + DateUtils.getTime(stratTime, "yyyy-M-dd"));
        if (DateUtils.getTime(endTime, "yyyy-M-dd") < DateUtils.getTime(stratTime, "yyyy-M-dd")) {
            UiUtils.Toast("请假的结束时间必须大于开始时间", false);
            return;
        }


        //获取请假事由
        String reason = etInput.getText().toString().trim();
        if (TextUtils.isEmpty(reason)) {
            //
            UiUtils.Toast("请完善请假信息", false);
            return;
        }

        Map<String, String> map = new HashMap<>();
        map.put("type", "2");
        map.put("acc", AccountUtils.getAccount(this));
        map.put("role", AccountUtils.getRole(this));
        map.put("apptoken", AccountUtils.getToken(this));
//        map.put("acc", "18827399806");
//        map.put("role", "1");
//        map.put("apptoken", "0");
        map.put("platform", "8");
        map.put("content", reason);
        map.put("begindate", stratTime);
        map.put("enddate", endTime);

//        Log.i("test", "开始时间" + stratTime + "结束时间" + endTime);

        CustomDialogManager.show(this, "提交中...");

        HttpUtils.post(HttpAdress.LEAVEONLINE, map, this, new HttpUtils.CallBack() {
            @Override
            public void onError(Call call, Exception e, int id) {
                CustomDialogManager.dissmiss();
                UiUtils.Toast(BaseApplication.ERROR, false);
            }

            @Override
            public void onResponse(String response, int id) {
                CustomDialogManager.dissmiss();
                if (!TextUtils.isEmpty(response)) {
                    ResultInfo info = null;
                    try {
                        info = GsonUtil.jsonToBean(response, ResultInfo.class);
                    } catch (Exception e) {
                        Log.i("test", "数据解析异常");
                    }

                    if (null != info) {
                        if ("200".equals(info.state)) {
                            //发送请假列表更新的消息
                            BusInfo busInfo = new BusInfo();
                            busInfo.msg = ParentsLeaveListActivity.LEAVEONLINE;
                            EventBus.getDefault().post(busInfo);
                            UiUtils.Toast("已完成请假，请耐心等待老师批假吧", false);
                            //返回成功
                            finish();

                        } else {
                            UiUtils.Toast("提交失败,返回错误码:" + info.state, false);
                            Log.i("test", "返回器返回异常,错误码是:" + info.state);
                        }
                    }
                } else {
                    Log.i("test", "服务返回数据异常");
                }
            }
        });
    }

    /**
     * 时间选择器
     */
    private void showChooseTimePicker(int type) {
        PickerManager.showPickerByYeaerAndMonthAndDay(this, new PickerManager.onSelectedListener() {
            @Override
            public void onTimeSelect(Date date, View v) {
                if (type == 1) {
                    //记录选择的开始时间
                    stratTime = DateUtils.getTime(date, "yyyy-M-dd");
                    tvStartTime.setText(DateUtils.getTime(date, "yyyy年-MM月-dd日"));
                } else if (type == 2) {
                    endTime = DateUtils.getTime(date, "yyyy-M-dd");
                    tvEndTime.setText(DateUtils.getTime(date, "yyyy年-MM月-dd日"));
                }
            }
        });
    }
}
